<template>
  <DashboardLayout
    title="个人中心"
    logo-icon="👤"
    :username="username"
    user-type="user"
    :active-menu="activeMenu"
    :current-title="getCurrentTitle()"
    breadcrumb-home="个人中心"
    @menu-select="handleMenuSelect"
    @logout="handleLogout"
  >
    <template #menu>
      <el-menu-item index="profile">
        <el-icon><User /></el-icon>
        <span>个人资料</span>
      </el-menu-item>
      <el-menu-item index="reviews">
        <el-icon><Star /></el-icon>
        <span>我的评价</span>
      </el-menu-item>
      <el-menu-item index="settings">
        <el-icon><Setting /></el-icon>
        <span>账户设置</span>
      </el-menu-item>
    </template>

    <template #content>
      <!-- 个人资料 -->
      <div v-if="activeMenu === 'profile'" class="content-section">
        <div class="section-header">
          <h2>个人资料</h2>
          <p>查看和编辑您的个人信息</p>
        </div>
        
        <div class="profile-container">
          <el-card class="profile-card">
            <div class="profile-info">
              <div class="avatar-section">
                <el-avatar :size="80" src="/toux.png" />
              </div>
              <div class="info-section">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="用户名">
                    {{ userProfile.username || '未设置' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="注册时间">
                    {{ formatDate(userProfile.registerTime) || '未知' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="最后登录">
                    {{ formatDate(userProfile.lastLoginTime) || '未知' }}
                  </el-descriptions-item>
                  <el-descriptions-item label="账户状态">
                    <el-tag type="success">正常</el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      
      <!-- 我的评价 -->
      <div v-if="activeMenu === 'reviews'" class="content-section">
        <div class="section-header">
          <h2>我的评价</h2>
          <p>查看您对美食的所有评价记录</p>
        </div>
        
        <div class="reviews-container">
          <div v-loading="reviewsLoading" class="reviews-content">
            <div v-if="reviews.length > 0">
              <div class="reviews-grid">
                <el-card v-for="review in reviews" :key="review.ratingId" class="review-card">
                  <div class="review-item">
                    <div class="review-food">
                      <el-image 
                        :src="getImageUrl(review.foodImagePath)" 
                        :alt="review.foodName" 
                        class="food-image"
                        fit="cover"
                      >
                        <template #error>
                          <el-image src="/food.png" class="food-image" fit="cover" />
                        </template>
                      </el-image>
                      <div class="food-info">
                        <h4>{{ review.foodName }}</h4>
                        <p class="restaurant-name">{{ review.merchantName }}</p>
                        <div class="rating-section">
                          <el-rate :model-value="parseFloat(review.rating) || 0" disabled size="small" />
                          <span class="rating-text">{{ review.rating }}分</span>
                        </div>
                      </div>
                    </div>
                    <div class="review-meta">
                      <el-tag size="small" type="info">{{ formatDate(review.ratingTime) }}</el-tag>
                    </div>
                  </div>
                </el-card>
              </div>
              
              <!-- 分页 -->
              <CustomPagination
                v-model:current-page="pagination.page"
                v-model:page-size="pagination.size"
                :total="pagination.total"
                :page-sizes="[10, 20, 50]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
            <div v-else-if="!reviewsLoading" class="empty-state">
              <el-empty description="您还没有评价过任何菜品">
                <el-button type="primary" @click="goToRecommendations">去看看推荐菜品</el-button>
              </el-empty>
            </div>
          </div>
        </div>
      </div>

      <!-- 账户设置 -->
      <div v-if="activeMenu === 'settings'" class="content-section">
        <div class="section-header">
          <h2>账户设置</h2>
          <p>管理您的账户安全设置</p>
        </div>
        
        <div class="settings-container">
          <el-card class="settings-card">
            <h3>密码管理</h3>
            <p class="settings-desc">定期更改密码可以提高账户安全性</p>
            <el-button type="primary" @click="showPasswordDialog = true">修改密码</el-button>
          </el-card>
          
          <el-card class="settings-card">
            <h3>账户安全</h3>
            <p class="settings-desc">保护您的账户免受未授权访问</p>
            <div class="security-items">
              <div class="security-item">
                <span>登录密码</span>
                <el-tag type="success">已设置</el-tag>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </template>
  </DashboardLayout>
  
  <!-- 修改密码对话框 -->
  <el-dialog v-model="showPasswordDialog" title="修改密码" width="500px">
    <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input v-model="passwordForm.currentPassword" type="password" show-password placeholder="请输入当前密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="changePassword" :loading="passwordLoading">确认修改</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { User, Star, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DashboardLayout from '@/components/DashboardLayout.vue'
import CustomPagination from '@/components/CustomPagination.vue'

export default {
  name: 'UserDashboard',
  components: {
    User,
    Star,
    Setting,
    DashboardLayout,
    CustomPagination
  },
  data() {
    return {
      activeMenu: 'profile',
      username: localStorage.getItem('username') || '用户',
      userProfile: {
        username: localStorage.getItem('username') || '',
        avatarPath: '',
        registerTime: '',
        lastLoginTime: ''
      },
      // 评价相关数据
      reviews: [],
      reviewsLoading: false,
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      // 修改密码相关
      showPasswordDialog: false,
      passwordLoading: false,
      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        currentPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadUserProfile()
    if (this.activeMenu === 'reviews') {
      this.loadReviews()
    }
  },
  methods: {
    getCurrentTitle() {
      const titles = {
        profile: '个人资料',
        reviews: '我的评价',
        settings: '账户设置'
      }
      return titles[this.activeMenu] || '概览'
    },
    
    handleMenuSelect(index) {
      this.activeMenu = index
      if (index === 'reviews') {
        this.loadReviews()
      }
    },
    
    handleLogout() {
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
      localStorage.removeItem('username')
      localStorage.removeItem('userId')
      localStorage.removeItem('adminId')
      localStorage.removeItem('merchantId')
      
      this.$router.push('/')
      ElMessage.success('退出登录成功')
    },
    
    // 加载用户资料
    async loadUserProfile() {
      try {
        const token = localStorage.getItem('token')
        const response = await fetch('http://localhost:2077/api/auth/me', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success && data.data.user) {
            this.userProfile = {
              username: data.data.user.username || localStorage.getItem('username') || '',
              avatarPath: data.data.user.avatarPath || '/toux.png',
              registerTime: data.data.user.registerTime || '',
              lastLoginTime: data.data.user.lastLoginTime || ''
            }
          }
        }
      } catch (error) {
        console.error('加载用户资料失败:', error)
      }
    },
    
    // 加载评价数据
    async loadReviews() {
      this.reviewsLoading = true
      try {
        const token = localStorage.getItem('token')
        
        const response = await fetch(`http://localhost:2077/api/reviews/user?page=${this.pagination.page}&size=${this.pagination.size}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          
          if (data.success) {
            this.reviews = data.data.data || []
            this.pagination.total = data.data.total || 0
          } else {
            ElMessage.error(data.message || '加载评价数据失败')
          }
        }
      } catch (error) {
        console.error('加载评价失败:', error)
      } finally {
        this.reviewsLoading = false
      }
    },
    
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.size = val
      this.pagination.page = 1
      this.loadReviews()
    },
    
    handleCurrentChange(val) {
      this.pagination.page = val
      this.loadReviews()
    },
    
    // 修改密码
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    },
    
    async changePassword() {
      try {
        await this.$refs.passwordFormRef.validate()
        this.passwordLoading = true
        
        const token = localStorage.getItem('token')
        const response = await fetch('http://localhost:2077/api/user/change-password', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            currentPassword: this.passwordForm.currentPassword,
            newPassword: this.passwordForm.newPassword
          })
        })
        
        const result = await response.json()
        
        if (result.success) {
          ElMessage.success('密码修改成功')
          this.showPasswordDialog = false
          this.resetPasswordForm()
        } else {
          ElMessage.error(result.message || '密码修改失败')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('网络错误，请稍后重试')
      } finally {
        this.passwordLoading = false
      }
    },
    
    resetPasswordForm() {
      this.passwordForm = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      if (this.$refs.passwordFormRef) {
        this.$refs.passwordFormRef.resetFields()
      }
    },
    
    // 工具方法
    getImageUrl(path) {
      if (!path) return '/food.png'
      if (path.startsWith('http')) return path
      return path.startsWith('/') ? path : `/${path}`
    },
    
    formatDate(dateString) {
      if (!dateString) return '未知'
      return new Date(dateString).toLocaleString('zh-CN')
    },
    
    goToRecommendations() {
      this.$router.push('/popular')
    }
  }
}
</script>

<style scoped>
.content-section {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
}

.section-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.section-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.section-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 个人资料样式 */
.profile-container {
  max-width: 800px;
}

.profile-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.profile-info {
  display: flex;
  gap: 32px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 120px;
}

.info-section {
  flex: 1;
}

/* 评价样式 */
.reviews-container {
  max-width: 1000px;
}

.reviews-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.review-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.review-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.review-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.review-food {
  display: flex;
  gap: 12px;
}

.food-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  flex-shrink: 0;
}

.food-info {
  flex: 1;
  min-width: 0;
}

.food-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.restaurant-name {
  margin: 0 0 8px 0;
  color: #6b7280;
  font-size: 14px;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-text {
  font-size: 14px;
  color: #6b7280;
  font-weight: 500;
}

.review-meta {
  display: flex;
  justify-content: flex-end;
}

/* 设置样式 */
.settings-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 24px;
  max-width: 1000px;
}

.settings-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 24px;
}

.settings-card h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.settings-desc {
  margin: 0 0 16px 0;
  color: #6b7280;
  font-size: 14px;
}

.security-items {
  margin-top: 16px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.security-item:last-child {
  border-bottom: none;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-info {
    flex-direction: column;
    text-align: center;
    gap: 24px;
  }
  
  .reviews-grid {
    grid-template-columns: 1fr;
  }
  
  .settings-container {
    grid-template-columns: 1fr;
  }
  
  .content-section {
    padding: 16px;
  }
  }
</style> 